package com.example.mapping.manage.processor;

import com.example.mapping.entity.process.JsonMappingProcessInfo;
import com.example.mapping.entity.JsonMappingSpec;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.stereotype.Component;

/**
 * json值处理器
 *
 * @author baoyoujia
 * @date 2022/10/20
 */
@Component
public class JsonValueProcessor implements Processor<JsonMappingProcessInfo> {
    @Override
    public void handle(JsonMappingProcessInfo jsonMappingProcessInfo) {
        for (JsonNode jsonNode : jsonMappingProcessInfo.getNodes()) {
            if (jsonNode instanceof ArrayNode) {
                for (JsonNode node : jsonNode) {
                    replace(node, jsonMappingProcessInfo.getJsonMappingSpec());
                }
            } else {
                replace(jsonNode, jsonMappingProcessInfo.getJsonMappingSpec());
            }
        }
    }

    public void replace(JsonNode jsonNode, JsonMappingSpec jsonMappingSpec) {
        JsonNode parent = jsonNode.findParent(jsonMappingSpec.getSrc());
        ObjectNode objectNode = (ObjectNode) parent;
        objectNode.put(jsonMappingSpec.getSrc(), jsonMappingSpec.getDest());
    }
}
